package com.study.controller.system;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.study.common.JsonDTo;
import com.study.common.constant.ResultCode;
import com.study.model.Admin;
import com.study.service.AdminService;
import com.study.util.FileCodeMD5;
import com.study.util.MD5Util;
import com.study.util.Page;
import com.study.util.StringUtil;

@Controller
public class AdminController {

	private Logger logger = Logger.getLogger(getClass());

	@Autowired
	private AdminService adminService;

	@RequestMapping(value = "/admin/getLoginInfo")
	public @ResponseBody JsonDTo loginInfo(HttpServletRequest request, HttpServletResponse response) {
		JsonDTo result = new JsonDTo();
		Admin manager = null;
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		String checkCode = request.getParameter("checkCode");
		String check_code = request.getSession().getAttribute("check_code").toString();
		if (!check_code.equalsIgnoreCase(checkCode)) {
			result.setCode(ResultCode.fail.value());
			result.setMsg("输入验证码不正确");
			logger.info("输入验证码不正确");
			return result;
		}
		try {
			password = FileCodeMD5.Md5(password);
			manager = adminService.getLoginInfo(account);
		} catch (Exception e) {
			e.printStackTrace();
			try {
				response.sendRedirect("/login.jsp");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			logger.info(e.getMessage(), e);
			result.setCode("0");
			result.setMsg(e.getMessage());
			return result;
		}
		if (manager == null) {
			result.setCode(ResultCode.manager_not_exist.value());
			result.setMsg(account + "用户不存在");
			logger.info(account + "user not exist");
		} else if (!password.equals(manager.getPassword())) {
			result.setCode(ResultCode.password_mistake.value());
			result.setMsg("密码错误");
			logger.info("password error");
		} else {
			result.setCode(ResultCode.success.value());
			result.setMsg(ResultCode.success.getDisplay());
			request.getSession().setAttribute("manager", manager);
			request.getSession().setAttribute("account", manager.getAccount());
			logger.info("Landing successful");
		}
		return result;
	}

	@RequestMapping(value = "/admin/list")
	public String list(HttpServletRequest request, HttpServletResponse response) {
		return "admin/adminList.jsp";
	}

	@RequestMapping(value = "/admin/getPaginate")
	public @ResponseBody Page getPaginateManagers(HttpServletRequest request, HttpServletResponse response) {
		Page results = new Page();
		try {
			results.setPageNo(Integer.parseInt(request.getParameter("pageNo")));
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("page", (results.getPageNo() - 1) * results.getPageSize());
			paramMap.put("pageSize", results.getPageSize());
			paramMap.put("searchValue", request.getParameter("searchValue"));

			paramMap.put("account", request.getSession().getAttribute("account").toString());
			List<Admin> objects = adminService.getPaginate(paramMap);

			int total = adminService.getTotal(paramMap);
			results.setTotalPages(results.getPages(total));
			results.getResult().addAll(objects);
		} catch (Exception e) {
			logger.error("/admin/getPaginate" + e.getMessage());
		}
		return results;
	}

	@RequestMapping(value = "/admin/toAdd")
	public String toAdd(HttpServletRequest request, HttpServletResponse response) {
		return "admin/adminAdd.jsp";
	}

	@RequestMapping(value = "/admin/toEdit")
	public String toEdit(HttpServletRequest request, HttpServletResponse response) {
		request.setAttribute("id", request.getParameter("id"));
		return "admin/adminEdit.jsp";
	}

	@RequestMapping(value = "/admin/get")
	public @ResponseBody JsonDTo get(HttpServletRequest request, HttpServletResponse response, Admin manager) {
		try {
			manager = adminService.get(manager);
			return new JsonDTo(ResultCode.success.value(), ResultCode.success.getDisplay(), manager);
		} catch (Exception e) {
			logger.error("admin/get:" + e.getMessage());
			return JsonDTo.getFail();
		}
	}

	@RequestMapping(value = "/admin/resetPass")
	public String resetPass(HttpServletRequest request, HttpServletResponse response, Admin manager) {
		if (manager.getId() != null) {
			manager = adminService.get(manager);
			request.setAttribute("account", manager.getAccount());
		}
		return "admin/resetPass.jsp";
	}

	@RequestMapping(value = "/admin/toeditPass")
	public String toeditPass(HttpServletRequest request, HttpServletResponse response, Admin manager) {
		if (manager.getId() != null) {
			manager = adminService.get(manager);
			request.setAttribute("account", manager.getAccount());
		}
		return "admin/editPass.jsp";
	}

	@RequestMapping(value = "/admin/save")
	public @ResponseBody JsonDTo save(HttpServletRequest request, HttpServletResponse response, Admin manager) {
		JsonDTo result = new JsonDTo();
		try {
			adminService.save(manager);
			result.setCode(ResultCode.success.value());
			result.setMsg("保存成功");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("/admin/save," + e.getMessage());
			result.setCode(ResultCode.fail.value());
			result.setMsg(e.getMessage());
		}
		return result;
	}

	@RequestMapping(value = "/admin/update")
	public @ResponseBody JsonDTo update(HttpServletRequest request, HttpServletResponse response, Admin manager) {
		try {
			adminService.update(manager);
			return JsonDTo.getSuccess();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("/admin/update," + e.getMessage());
			return JsonDTo.getFail();
		}
	}

	@RequestMapping(value = "/admin/editPassWord")
	public @ResponseBody JsonDTo editPassWord(HttpServletRequest request, HttpServletResponse response, Admin manager) {
		try {
			adminService.editPassWord(manager);
			return JsonDTo.getSuccess();
		} catch (Exception e) {
			logger.error("admin/editPassWord: " + e.getMessage());
			return JsonDTo.getFail();
		}
	}

	@RequestMapping(value = "/admin/isExistByName")
	public @ResponseBody JsonDTo IsExistByName(HttpServletRequest request, HttpServletResponse response,
			Admin manager) {
		try {
			Admin obj = adminService.isExistByName(manager);
			if (StringUtil.isBlank(manager.getId())) {
				if (obj == null) {
					// 可以直接添加
					return JsonDTo.getFail();
				} else {
					// 已经存在 不可以添加
					return JsonDTo.getSuccess();
				}
			} else {
				if (obj == null || obj.getId() == manager.getId()) {
					// 可以直接添加
					return JsonDTo.getFail();
				} else {
					return JsonDTo.getSuccess();
				}
			}
		} catch (Exception e) {
			logger.error("/admin/isExistByName: " + e.getMessage());
			return JsonDTo.getSuccess();
		}
	}

	@RequestMapping(value = "/admin/removeList")
	public @ResponseBody JsonDTo removeList(HttpServletRequest request, HttpServletResponse response) {
		try {
			adminService.remove(request.getParameter("ids"));
			return JsonDTo.getSuccess();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return JsonDTo.getFail();
		}
	}

	@RequestMapping(value = "/admin/isOldpasswordRight")
	public @ResponseBody JsonDTo isOldpasswordRight(HttpServletRequest request, HttpServletResponse response) {
		try {
			Admin manager = (Admin) request.getSession().getAttribute("manager");
			if (MD5Util.Md5(request.getParameter("oldpassword")).equals(manager.getPassword())) {
				return JsonDTo.getFail();
			} else {
				return JsonDTo.getSuccess();
			}
		} catch (Exception e) {
			logger.error("/admin/isOldpasswordRight: " + e.getMessage());
			return JsonDTo.getFail();
		}
	}

}